package com.zixun.service.Impl;

import com.zixun.model.information.Information;
import com.zixun.repository.information.InformationRepository;
import com.zixun.service.InformationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;

/**
 * Created by Basil on 16/8/22.
 */
@Service
public class InformationServiceImpl implements InformationService{

    @Autowired
    InformationRepository informationRepository;

    @Override
    public Page<Information> findPageByUserId(final Integer userId, Integer pageIndex, Integer countPerPage) {
        Specification<Information> informationSpecification = new Specification<Information>(){

            @Override
            public Predicate toPredicate(Root<Information> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                return null;
            }
        };
        Pageable pageable = new PageRequest(pageIndex - 1, countPerPage);
        return informationRepository.findAll(informationSpecification, pageable);
    }

    @Override
    public Information findInformationByInformationId(Integer informationId) {
        Information information = informationRepository.findById(informationId);
        return information;
    }

    @Override
    public Page<Information> findAllByLikeTitle(final String title, Integer pageIndex, Integer countPerPage) {

        Specification<Information> informationSpecification = new Specification<Information>() {
            @Override
            public Predicate toPredicate(Root<Information> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<String> _title = root.get("title");
                Predicate _key = cb.like(_title,"%"+title+"%");
                return cb.and(_key);
            }
        };
        Pageable pageable = new PageRequest( pageIndex- 1, countPerPage);
        return informationRepository.findAll(informationSpecification,pageable);
    }

}
